<template>
	<view class="chart-cont"><l-echart class="chart" ref="chartRef"></l-echart></view>
</template>
<script setup lang="ts">
	import { onMounted, ref, reactive, getCurrentInstance } from 'vue';

	const { proxy } = getCurrentInstance();

	const echarts = require('../../../uni_modules/lime-echart/static/echarts.min');
	const chartRef = ref(null);
	const myChart = ref(null);
	const xData = ref([]);
	const yNowData = ref([]);
	const yLastData = ref([]);
	const option = reactive({
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				//阴影指示器
				type: 'shadow'
			},
			confine: true
		},
		legend: {
			top: 10,
			left: "center",
			itemWidth: 10,
			itemHeight: 5,
			data: ['本月', '上月'],
		},
		grid: {
			top: 40,
			left: 20,
			right: 10,
			bottom: 20,
			containLabel: true,
		},
		xAxis: [
			{
				type: 'category',
				axisTick: {
					show: false
				},
				axisLine: {
					lineStyle: {
						color: "#e1e1e1"
					}
				},
				axisLabel: {
					color: '#999'
				},
				data: xData.value,
			}
		],
		yAxis: [
			{
				type: 'value',
				// min: 0,
				// max: 50,
				// interval: 5,
				axisLabel: {
					color: '#999'
				},
			}
		],
		series: [
			{
				name: '本月',
				type: 'bar',
				barWidth: 10,
				tooltip: {
					valueFormatter: function (value) {
						return value;
					},
				},
				itemStyle: {
					color: "#86D06A",
					borderColor: "#51B52A",
					borderWidth: 1,
				},
				data: yNowData.value,
			},
			{
				name: '上月',
				type: 'bar',
				barWidth: 10,
				tooltip: {
					valueFormatter: function (value) {
						return value;
					},
				},
				itemStyle: {
					color: "#FFBB73",
					borderColor: "#E8851D",
					borderWidth: 1,
				},
				data: yLastData.value,
			},
		]
	});

	onMounted(() => {

	});

	async function initChart() {
		if (!chartRef.value) return
		const chart = await chartRef.value.init(echarts)
		chart.setOption(option)
		myChart.value = chart
	}


	const initData = (keys, data, lastData) => {

		xData.value.length = 0;
		yNowData.value.length = 0;
		yLastData.value.length = 0;
		data[keys].forEach(item => {
			xData.value.push(proxy.dayjs(item.time).format('MM-DD'));
			yNowData.value.push(item.value);

			for (let i = 0; i < lastData[keys].length; i++) {
				if (proxy.dayjs(lastData[keys][i].time).format("YYYY-DD") == proxy.dayjs(item.time).format("YYYY-DD")) {
					yLastData.value.push(lastData[keys][i].value)
					break;
				}
			}
		})
	
		// 组件能被调用必须是组件的节点已经被渲染到页面上
		setTimeout(() => {
			initChart()
		}, 300)
	}

	defineExpose({
		initData
	})
</script>
<style lang="scss" scoped>
	.chart-cont {
		position: relative;
		width: 100%;
		height: 100%;

		.chart {
			width: 100%;
			height: 100%;
		}
	}
</style>